/*
 * Copyright (C), 2010-2017, ATCOM Tech. Co., Ltd.
 *
 * File Name: threadpool.h
 * Author: liaoxuecheng
 * mail: 872958436@qq.com
 * Created Time: Tue 01 Sep 2020 08:58:32 AM CST
 *
 */

#ifndef _THREADPOOL_H_
#define _THREADPOOL_H_

#include <pthread.h>

typedef enum {
    THREADPOOL_CREATE_SUCCESS   = 0,
    THREADPOOL_CREATE_PARAM_ERR = -1,
    THREADPOOL_INVALID          = -2,
    THREADPOOL_LOCK_FAILURE     = -3,
    THREADPOOL_QUEUE_FULL       = -4,
    THREADPOOL_SHUTDOWN         = -5,
    THREADPOOL_THREAD_FAILURE   = -6,
    THREADPOOL_MALLOC_ERR       = -7,
    THREADPOOL_CREATE_THREAD_ERR= -8,
} threadpool_error_t;

enum
{
    THREADPOOL_MAX_QUEUE_SIZE       = 1 << 0,
    THREADPOOL_MIDDLE_QUEUE_SIZE    = 1 << 1,
    THREADPOOL_MAX_THREADS          = 1 << 2,
    THREADPOOL_MIDDLE_THREADS       = 1 << 3,
    THREADPOOL_CLOSE_IMMEDIATELY    = 1 << 4,
    THREADPOOL_CLOSE_IMDY_ANDABORT  = 1 << 5,
};

#define DEFAULT_SIZE 0

#define MIN_QUEUE_SIZE 16
#define MIDDLE_QUEUE_SIZE 256
#define MAX_QUEUE_SIZE 65536

#define MIN_THREADS 8
#define MIDDLE_THREADS 32
#define MAX_THREADS 64

typedef struct
{
    void (*func)(void *);
    void *arg;
}threadpool_task_t;

typedef struct
{
    pthread_mutex_t mutex;
    pthread_cond_t queue_empty;
    pthread_cond_t queue_not_empty;
    pthread_cond_t queue_not_full;

    pthread_t *threads;
    int thread_count;
    threadpool_task_t *queue;
    int queue_max_num;
    int queue_cur_num;

    int head;
    int tail;
    int pool_close;
    int flags;
}threadpool_t;

extern int threadpool_destory(threadpool_t *pool);
extern int threadpool_create(threadpool_t **pool, int thread_count, int queue_size, int flags);
extern int threadpool_add_job(threadpool_t *pool, void(*callback_func)(void *), void *arg, int flags);

#endif //_THREADPOOL_H_
